package ee.ut.maxorato_macobo.oop.mud.game;

import java.util.TreeMap;

public class GameArea {
	private static TreeMap<String, GameArea> areaList = new TreeMap<String, GameArea>();
	
	public static GameArea createArea(String newAreaName) {
		if(GameArea.findAreaByName(newAreaName) != null) return null;
		
		GameArea newArea = new GameArea(newAreaName);
		areaList.put(newAreaName, newArea);
		return newArea;
	}
	
	public static GameRoom getStartRoom() {
		if(areaList.firstEntry() == null) return null;
		
		GameArea area = areaList.firstEntry().getValue();
		
		if(area.getRoomList().firstEntry() == null) return null;
		
		return area.getRoomList().firstEntry().getValue();
	}
	
	public static TreeMap<String, GameArea> getAreaList() {
		return areaList;
	}
	
	public static GameArea findAreaByName(String findAreaName) {
		return areaList.get(findAreaName);
	}
	
	public static GameRoom findRoomByAreaAndIndex(String areaName, int roomIndex) {
		GameArea targetArea = findAreaByName(areaName);
		if(targetArea == null) return null;
		
		return targetArea.findRoom(roomIndex);
	}
	
	public static String getAreaNameFromIdent(String roomIdent) {
		String[] splits = roomIdent.split(",");
		if(splits.length != 2) return "default";
		
		return splits[0];
	}
	
	public static int getRoomIndexFromIdent(String roomIdent) {
		String[] splits = roomIdent.split(",");
		if(splits.length != 2) return Integer.parseInt(splits[0]);
		
		return Integer.parseInt(splits[1]);
	}
	
	public static GameRoom findRoomByIdent(String roomIdent) {
		if(roomIdent == null) return null;
		
		String[] splits = roomIdent.split(",");
		if(splits.length != 2) return findRoomByAreaAndIndex("default", Integer.parseInt(splits[1]));
		
		return findRoomByAreaAndIndex(splits[0], Integer.parseInt(splits[1]));
	}
	
	private TreeMap<Integer, GameRoom> areaRooms;
	private String areaName;
	
	private GameArea(String newAreaName) {
		areaName = newAreaName;
		areaRooms = new TreeMap<Integer, GameRoom>();
	}
	
	public void addRoom(GameRoom room) {
		areaRooms.put(room.getRoomIndex(), room);
	}
	
	public GameRoom findRoom(int roomIndex) {
		return areaRooms.get(roomIndex);
	}
	
	public TreeMap<Integer, GameRoom> getRoomList() {
		return areaRooms;
	}
	
	public String getAreaName() {
		return areaName;
	}
}
